package cn.redragon.soa.common.dto;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Positive;
import lombok.Data;
import lombok.SneakyThrows;
import org.apache.commons.codec.binary.Base64;
import org.springframework.validation.annotation.Validated;

@Validated
@Data
public class JwtSecurityProperty {

    private PrivateKey tokenGenerateKey;

    private String privateKey;

    @NotBlank
    private String issuer;

    @Positive
    private Long expiration;

    @NotBlank
    private String clientId;

    @SneakyThrows
    public synchronized PrivateKey getTokenGenerateKey() {
        if (tokenGenerateKey != null) {
            return tokenGenerateKey;
        }

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] encodedPv = Base64.decodeBase64(privateKey);
        PKCS8EncodedKeySpec keySpecPv = new PKCS8EncodedKeySpec(encodedPv);
        tokenGenerateKey = keyFactory.generatePrivate(keySpecPv);
        return tokenGenerateKey;
    }
}
